/**
 * 首页信息的js文件
 * @license MIT
 * @Author ${author}
 * @Date ${date}
 *
 */
("use strict");
layui.use(['jquery', 'layer', 'table' , 'laypage' , 'form', 'laydate', 'upload'], function () {

    var $ = layui.jquery;
    var layer = layui.layer;
    if (!window.$) window.$ = layui.$;

    /**
     * 统一的窗口偏移
     */
    const COMMON_OFFSET = ["60px", "230px"];
<#if ES_URIS??>

    /**
     * @method 聚合搜索hint题词转换
     * @param {*} hint  hint题词
     * @desc
     *    主要是将hint题词由带有html标签的字符串转化成可信任的带html标签的字符串
     * @returns
     */
    layui.transformElasticsearchHint = function (hint) {
        if (!hint) return "";
        var p = 0,
        p0 = 0,
        len = hint.length,
        res = "";
        while (p < len) {
            var s = "",
            sub = hint.substring(p);
            if (/^\s*<([A-z]+[0-9]?)(\s(\s*[^=<>]*\-?[^=<>\s]+\s*(=\s*(\"[^\"]*\"|\'[^\']*\'))?\s*)*)?\s*\/?>/.test(sub)) {
                res += hint.substring(p0, p);
                let matchRes = sub.match(/^\s*(<([A-z]+[0-9]?)(\s(\s*[^=<>]*\-?[^=<>\s]+\s*(=\s*(\"[^\"]*\"|\'[^\']*\'))?\s*)*)?\s*\/?>)/);
<#assign spanEntity = 'span' />
                res += '<${spanEntity} style = "color: red">';
                s = matchRes[1];
                p0 = p + s.length;
            } else if (/^\s*<\/([A-z]+[0-9]?)>/.test(sub)) {
                res += hint.substring(p0, p);
                let matchRes = sub.match(/^\s*(<\/([A-z]+[0-9]?)>)/);
                res += "</${spanEntity}>";
                s = matchRes[1];
                p0 = p + s.length;
            }
            p += s ? s.length : 1;
        }
        res += hint.substring(p0, p);
        return res;
    };
</#if>
    /**
     * @method 打开弹窗
     * @param {*} key  LAYER_CONFIG里面的key
     * @param {*} data
     * @desc
     *    主要是将url参数进行请求放入content配置项中
     *    然后再调用方法，打开弹层
     * @returns
     */
    layui.openLayer = function (key, data) {
        let option;
        if (_lodash.isString(key)) {
            let _option = LAYER_CONFIG[key];
            option = {
                id: key,
                name: _option.name || key,
                type: _option.type || 1,
                ignore: _option.ignore === true ? true : false,
                url: _option.url,
                area: _option.area,
                offset: _option.offset || COMMON_OFFSET,
                moudle: _option.moudle || key,
                autoBuild: _option.autoBuild || false,
            };
            if(_option.content) option.content = _option.content;
        } else {
            option = key;
        }
        if (!option.url) return layui.layer.open(option, data || {title: option.name});
        $.get(option.url, {}, (r) => {
            // TODO 处理html内容
            option.content = r;
            layui.layer.open(option, data);
        });
    };

    let mConfig = {
        groupOne: {
            id: "groupOne",
            mark: "a",
            name: "分组一",
        },
        groupTwo: {
            id: "groupTwo",
            mark: "b",
            name: "分组二",
        },
    };

    let tConfig = [
        {
            id: "groupOne",
            name: "分组一",
            source: [],
        },
        {
            id: "groupTwo",
            name: "分组二",
            source: [],
        },
    ];
    let index = 0;
    _lodash.each(LAYER_CONFIG, (v, k) => {
        if(v.pid && v.pid == 1){
            let parentKey = index % 2 == 0 ? 'groupOne' : 'groupTwo';
            mConfig[k] = {
                id: k,
                name: v.name,
                pid: parentKey,
            };
            tConfig[index % 2].source.push({
                id: k,
                name: v.name,
                x: tConfig[index % 2].source.length % 3,
                y: Math.floor(tConfig[index % 2].source.length / 3),
                w: 1,
                h: 1,
            });
            index ++;
        }
    });
    /**
     * 初始化登录对象
     * 需要传入随机的crc值。请注意，这个crc值最好随机生成
     */
    var login = layui.enableLogin("33b03e33-e570-4669-8a74-cd69ce749d20").login;
<#if ES_URIS??>

    // 初始化聚合搜索对象
    var search = layui.enableSearch().search;
</#if>
    /**
     * ajax请求设置,比如和header添加token，请求结果为401跳到登录等。
     */
    $.ajaxSetup({
        xhrFields: {
            withCredentials: true,
        },
        crossDomain: true,
        beforeSend: function (xhr, obj) {
            let users = layui.sessionData(LAYUI_USER_FIELD);
            xhr.setRequestHeader(
                "Authorization",
                (users.data && users.data.token) || ""
            );
        },
        error: function (e) {
            if (e.status == 401) login.afterLogout();
            if (e.status == 403) layui.layer.msg("您没有操作权限", { icon: 5 });
        },
        complete: function (xhr, textStatus) {
            if (xhr.status == 401) login.afterLogout();
            if (xhr.status == 403) layui.layer.msg("您没有操作权限", { icon: 5 });
        },
    });
    // 检查一下当前是否登录(token是否还有效)
    login.touch();


    /**
     * 初始化操作栏
     */
    layui.layer.enableTabs({
        MENU_CLICK_EVENT: function(id){
            // 自定义菜单点击事件
            layui.openLayer(id);
        },
        LOGOUT_EVENT: function () {
            // 自定义点击退出按钮事件
            login.logout();
        },
<#if ES_URIS??>
        SHOW_SEARCH_EVENT: function () {
            // 自定义打开搜索栏事件
            search.start();
        },
        HIDE_SEARCH_EVENT: function () {
            // 自定义关闭搜索栏事件
            if (!search.stop()) {
                layui.windows.instance().$data.searchVisable = "true";
                return false;
            }
            return true;
        },
        SEARCH_EVENT: function (v) {
            // 自定义搜索值改变事件
            search.change(v);
        },
</#if>
    },mConfig);

    let container = $(
        `<div class = "layui-layer-tiles layui-windows-desk-scroll"></div>`
    );
    $(".layui-windows-desk").append(container);

    layui.tile(container, { data: tConfig })
        .setAnimate(['flip', 'bounceIn', 'flash', 'pulse', 'rubberBand', 'shake', 'headShake', 'swing'], 0.5);

    layui.windows.instance().$data.menusVisable = 'true';
});
